package nl.depository.pim.pages.admin.form;

import javax.mail.internet.InternetAddress;

import nl.depository.pim.ObjectValueEncoder;
import nl.depository.pim.entities.Contact;
import nl.depository.pim.entities.Website;
import nl.depository.pim.pages.Dashboard;
import nl.depository.pim.services.DataService;

import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;

public class ContactForm
{
	private String contactId;
	
	@Property
	private Contact contact;
	
	@SuppressWarnings("unused")
	@Persist
	@Property(write=false)
	private ObjectValueEncoder encoder;
	
	@SuppressWarnings("unused")
	@Property
	private InternetAddress mailAddress;

	@SuppressWarnings("unused")
	@Property
	private Website website;
	
	@Inject
	private DataService dataService;
	
	public void onActivate(String contactId)
	{
		this.contactId = contactId;
	}
	
	public String onPassivate()
	{
		return contactId;
	}
	
	public void onPrepare() throws Exception
	{
		encoder = new ObjectValueEncoder();
		
		contact = contactId != null
			? (Contact) dataService.retrieveRecord(contactId)
			: new Contact();
	}
	
	public InternetAddress onAddRowFromMailAddresses()
	{
		InternetAddress mailAddress = new InternetAddress();
		contact.getMailAddresses().add(mailAddress);
		return mailAddress;
	}
	
	public void onRemoveRowFromMailAddresses(InternetAddress mailAddress)
	{
		contact.getMailAddresses().remove(mailAddress);
	}

	public Website onAddRowFromWebsites()
	{
		Website website = new Website();
		contact.getWebsites().add(website);
		return website;
	}
	
	public void onRemoveRowFromWebsites(Website website)
	{
		contact.getWebsites().remove(website);
	}
	
	public void onValidateForm()
	{
		// FIXME: Investigate whether it throws an runtime exception if something goes wrong.
		dataService.save(contact);
	}
	
	public Object onSuccess()
	{
		return Dashboard.class;
	}
}
